import React, { useState } from 'react';
import { Rate, Typography, Image, Button, Space, message } from 'antd';
import { useLocation } from 'react-router-dom';
import { useAuthToken } from "../AuthTokenContext";
import '../style/detail.css';

const { Title, Paragraph, Text, Link } = Typography;
const MovieDetail = () => {
    const location = useLocation();
    const movieData = location.state;
    const { accessToken } = useAuthToken();
    // State to store the user's rating
    const [rating, setRating] = useState(movieData?.rating || 0);

    // Handle rating change
    const handleRatingChange = value => {
        setRating(value);
    };
    // Handle submit
    const handleSubmit = async () => {
        try {
            const response = await fetch(`${process.env.REACT_APP_API_URL}/updateRating`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'MovieDetaillication/json',
                    Authorization: `Bearer ${accessToken}`,
                },
                body: JSON.stringify({
                    ratingId: movieData.ratingId, // Assuming you have the rating ID in your movieData
                    newScore: rating,
                }),
            });
            const { message: msg } = await response.json();
            message.success(msg);
        } catch (error) {
            message.error(error);
        }
    };
    return (<Typography>
        <Title level={2}>{movieData?.title}</Title>
        <Paragraph>
            <Image
                width={150}
                src={movieData?.image}
            />

        </Paragraph>
        <Title level={3}>Movie Details Introduction</Title>

        <Paragraph>
            <Text strong>
                {movieData?.description}
            </Text>
        </Paragraph>
        <Title level={3}>Movie genre</Title>
        <Paragraph>
            <ul>
                {movieData?.genre.map((item, index) => {
                    return (
                        <li key={index}>
                            <Link href="#">{item}</Link>
                        </li>
                    )
                })}

            </ul>
        </Paragraph>
        <Title level={3}>Movie Rate</Title>
        <Paragraph>
            <Space align="baseline" size={70}>
                <Rate count={10} /* allowHalf */ value={rating} onChange={handleRatingChange} />
                <Button type="primary" htmlType="submit" onClick={handleSubmit}>
                    Submit
               </Button>
            </Space>
        </Paragraph>
    </Typography>)
}
export default MovieDetail;